package com.mxf.code.service.impl;


import com.mxf.code.mapper.SysUserDao;
import com.mxf.code.pojo.bo.LoginUser;
import com.mxf.code.pojo.entity.SysUser;
import com.mxf.code.pojo.vo.PermissionVO;
import com.mxf.code.service.PermissionService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : UserDetailsServiceImpl
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/3 17:11]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/3 17:11]
 * @updateRemark : [描述说明本次修改内容]
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = sysUserDao.selectByUserName(userName);

        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // TODO 获取对应的权限信息

        List<PermissionVO> permissionVOS = permissionService.listPermissionsByUserId(user.getId());
        List<String> collect = permissionVOS.stream().map(PermissionVO::getPerms).collect(Collectors.toList());
        // 用户信息封装
        return new LoginUser(user, collect);
    }
}
